package com.wdm.sms.controller.huawei;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.obs.services.exception.ObsException;
import com.wdm.sms.commonutil.utils.jwt.PassToken;
import com.wdm.sms.commonutil.utils.r.R;
import com.wdm.sms.service.huawei.HweiYunOBSService;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName: ObsController
 * @Description: OBS服务器Controller
 * @author: wudaiming
 * @date: 2023/3/21
 * @version: 1.0
 */
@RestController
 @RequestMapping("/file") //@RequestMapping({ "file" })
public class HweiYunOBSController {

    @Resource
    private HweiYunOBSService hweiYunOBSService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public R save(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (ObjectUtils.isEmpty(file)) {
            return R.buildFailure(20000,"文件为空");
        }
        final String test = hweiYunOBSService.fileUpload(file, file.getOriginalFilename());
        return R.ok(test);
    }

    @RequestMapping(value = "delete/{fileName}", method = RequestMethod.POST)
    public R delete(@PathVariable String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return R.buildFailure(20001,"删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileName);
        return delete?R.ok("删除成功"):R.buildFailure(20002,"删除失败");
    }

    @RequestMapping(value = "deletes", method = RequestMethod.POST)
    //@RequestParam 获取List，数组则不需要
    public R delete(@RequestParam("fileNames") List<String> fileNames) {
        if (ArrayUtil.isEmpty(fileNames)) {
            return R.buildFailure(20003,"删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileNames);
        return delete?R.ok("成功"):R.buildFailure(20004,"失败");
    }


    @RequestMapping(value = "download/{fileName}", method = RequestMethod.POST)
    public R download(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return R.buildFailure(20006,"下载文件为空");
        }
        try (InputStream inputStream = hweiYunOBSService.fileDownload(fileName);BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())){
            if(inputStream == null) {
                return R.buildFailure(20007,"失败");
            }
            // 为防止 文件名出现乱码
            final String userAgent = request.getHeader("USER-AGENT");
            // IE浏览器
            if (StrUtil.contains(userAgent, "MSIE")) {
                fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            } else {
                // google,火狐浏览器
                if (StrUtil.contains(userAgent, "Mozilla")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    // 其他浏览器
                    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
                }
            }
            response.setContentType("application/x-download");
            // 设置让浏览器弹出下载提示框，而不是直接在浏览器中打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            IoUtil.copy(inputStream, outputStream);
            return null;
        } catch (IOException | ObsException e) {
            return R.buildFailure(20009,"失败");
        }
    }

    @GetMapping(value = "/previewFile")
    @PassToken
    @ApiOperation(value = "根据objectKey预览", notes = "根据objectKey预览", httpMethod = "GET")
    public R previewFile(HttpServletRequest request, HttpServletResponse response, String objectKey) throws IOException {
        return hweiYunOBSService.previewFile(request, response, objectKey);
    }
}
